package com.tianshi.agriculture.ui.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.tianshi.agriculture.databinding.FieldDebugLayoutBinding;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.BleController;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.callback.OnReceiverCallback;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.callback.OnWriteCallback;
import com.tianshi.agriculture.utils.ModbusUtils.ByteUtil;
import com.tianshi.agriculture.utils.ModbusUtils.ModbusError;
import com.tianshi.agriculture.utils.ModbusUtils.ModbusRTUHelper;
import com.tianshi.agriculture.utils.ToolsUtil;

import java.util.Arrays;

public class FieldDebugFragment extends Fragment {

    private FieldDebugLayoutBinding binding;
    public static final String REQUESTKEY_SENDANDRECIVEACTIVITY = "FieldDebugFragment";

    // Modbus地址定义（从0开始）
    private static final int ADDRESS_INLET_PRESSURE = 26;      // 进水-满度压力
    private static final int ADDRESS_RETURN_PRESSURE = 34;     // 回水-满度压力
    private static final int ADDRESS_RETURN_TEMP_DRIFT = 42;    // 回水-温度零漂
    private static final int ADDRESS_INLET_TEMP_DRIFT = 50;    // 进水-温度零漂
    private static final int REGISTER_COUNT = 2;                // Float类型需要2个寄存器

    // 批量读取的起始地址和寄存器数量
    private static final int BATCH_READ_START_ADDRESS = 26;            // 起始地址
    private static final int BATCH_READ_REGISTER_COUNT = 26;           // 需要读取的寄存器数量 (从26到51，共26个寄存器)
    
    private boolean isBatchReading = false;  // 标记是否正在进行批量读取
    private int currentReadAddress = -1;  // 当前正在读取的地址，用于区分不同的读取响应（单个读取时使用）
    private Handler handler = new Handler(Looper.getMainLooper());  // 用于延迟执行读取操作
    
    // 地址到EditText的映射
    private java.util.Map<Integer, EditText> addressToEditTextMap = new java.util.HashMap<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        FieldDebugModel fieldDebugModel =
                new ViewModelProvider(this).get(FieldDebugModel.class);

        binding = FieldDebugLayoutBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化地址到EditText的映射
        initAddressMap();

        // 进水-满度压力读取按钮
//        binding.readInletPressureButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                readFloatValue(ADDRESS_INLET_PRESSURE, "进水-满度压力");
//            }
//        });

        // 进水-满度压力写入按钮
        binding.writeInletPressureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeFloatValue(ADDRESS_INLET_PRESSURE, binding.valueInletPressure.getText().toString(), "进水-满度压力");
            }
        });

        // 回水-满度压力读取按钮
//        binding.readReturnPressureButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                readFloatValue(ADDRESS_RETURN_PRESSURE, "回水-满度压力");
//            }
//        });

        // 回水-满度压力写入按钮
        binding.writeReturnPressureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeFloatValue(ADDRESS_RETURN_PRESSURE, binding.valueReturnPressure.getText().toString(), "回水-满度压力");
            }
        });

        // 回水-温度零漂读取按钮
//        binding.readReturnTempDriftButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                readFloatValue(ADDRESS_RETURN_TEMP_DRIFT, "回水-温度零漂");
//            }
//        });

        // 回水-温度零漂写入按钮
        binding.writeReturnTempDriftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeFloatValue(ADDRESS_RETURN_TEMP_DRIFT, binding.valueReturnTempDrift.getText().toString(), "回水-温度零漂");
            }
        });

//        // 进水-温度零漂读取按钮
//        binding.readInletTempDriftButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                readFloatValue(ADDRESS_INLET_TEMP_DRIFT, "进水-温度零漂");
//            }
//        });

        // 进水-温度零漂写入按钮
        binding.writeInletTempDriftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeFloatValue(ADDRESS_INLET_TEMP_DRIFT, binding.valueInletTempDrift.getText().toString(), "进水-温度零漂");
            }
        });

        // 读取所有按钮
        binding.readAllButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readAllValues();
            }
        });

        return root;
    }

    /**
     * 初始化地址到EditText的映射
     */
    private void initAddressMap() {
        addressToEditTextMap.put(ADDRESS_INLET_PRESSURE, binding.valueInletPressure);
        addressToEditTextMap.put(ADDRESS_RETURN_PRESSURE, binding.valueReturnPressure);
        addressToEditTextMap.put(ADDRESS_RETURN_TEMP_DRIFT, binding.valueReturnTempDrift);
        addressToEditTextMap.put(ADDRESS_INLET_TEMP_DRIFT, binding.valueInletTempDrift);
    }

    /**
     * 读取所有值 - 一次性读取所有寄存器，然后从返回值中提取需要的值
     */
    private void readAllValues() {
        Toast.makeText(getActivity(), "开始读取所有值...", Toast.LENGTH_SHORT).show();
        
        try {
            isBatchReading = true;
            // 一次性读取从起始地址开始的所有寄存器
            byte[] bytes = ModbusRTUHelper.readHoldingRegisters(1, BATCH_READ_START_ADDRESS, BATCH_READ_REGISTER_COUNT);
            System.out.println("发送批量读取所有寄存器:>>>" + BleController.getInstance().bytesToHexString(bytes));

            BleController.getInstance().writeBuffer(bytes, new OnWriteCallback() {
                @Override
                public void onSuccess() {
                    // 读取请求发送成功，等待响应
                }

                @Override
                public void onFailed(int state) {
                    Toast.makeText(getActivity(), "批量读取失败！", Toast.LENGTH_SHORT).show();
                    isBatchReading = false;
                }
            });
        } catch (ModbusError e) {
            Toast.makeText(getActivity(), "批量读取异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            isBatchReading = false;
        }
    }

    /**
     * 从批量读取的响应中提取指定地址的值
     * @param dataBytes 数据部分（不包含设备地址、功能码、字节数、CRC）
     * @param address 要提取的地址
     * @return 提取的Float值
     */
    private Float extractFloatValueFromBatchData(byte[] dataBytes, int address) {
        // 计算地址在批量数据中的偏移量（相对于起始地址）
        int offset = address - BATCH_READ_START_ADDRESS;
        
        // 检查偏移量是否有效
        if (offset < 0 || offset + 1 >= BATCH_READ_REGISTER_COUNT) {
            return null;
        }
        
        // Float类型需要2个寄存器（4个字节）
        int byteOffset = offset * 2; // 每个寄存器2个字节
        if (byteOffset + 3 >= dataBytes.length) {
            return null;
        }
        
        byte[] floatBytes = Arrays.copyOfRange(dataBytes, byteOffset, byteOffset + 4);
        return ByteUtil.bytesToFloat(floatBytes);
    }

    /**
     * 读取Float类型的值
     * @param address Modbus地址
     * @param name 参数名称（用于显示）
     */
    private void readFloatValue(int address, String name) {
        try {
            currentReadAddress = address;
            byte[] bytes = ModbusRTUHelper.readHoldingRegisters(1, address, REGISTER_COUNT);
            System.out.println("发送读取" + name + ":>>>" + BleController.getInstance().bytesToHexString(bytes));

            BleController.getInstance().writeBuffer(bytes, new OnWriteCallback() {
                @Override
                public void onSuccess() {
                    // 读取请求发送成功，等待响应
                }

                @Override
                public void onFailed(int state) {
                    Toast.makeText(getActivity(), name + "读取失败！", Toast.LENGTH_SHORT).show();
                    currentReadAddress = -1;
                }
            });
        } catch (ModbusError e) {
            Toast.makeText(getActivity(), name + "读取异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            currentReadAddress = -1;
        }
    }

    /**
     * 写入Float类型的值
     * @param address Modbus地址
     * @param valueStr 要写入的值（字符串）
     * @param name 参数名称（用于显示）
     */
    private void writeFloatValue(int address, String valueStr, String name) {
        if (valueStr == null || valueStr.trim().isEmpty()) {
            Toast.makeText(getActivity(), "请输入" + name + "的值", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!ToolsUtil.isFloatType(valueStr)) {
            Toast.makeText(getActivity(), name + "的值格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            float value = Float.parseFloat(valueStr);
            byte[] floatBytes = ByteUtil.floatToBytes(value);
            
            // 将float的4个字节转换为2个16位寄存器
            int[] writeInt16 = new int[REGISTER_COUNT];
            writeInt16[0] = ByteUtil.bytesToUint16(floatBytes[0], floatBytes[1]);
            writeInt16[1] = ByteUtil.bytesToUint16(floatBytes[2], floatBytes[3]);

            byte[] bytes = ModbusRTUHelper.writeHoldingRegisters(1, address, REGISTER_COUNT, writeInt16);
            System.out.println("发送写入" + name + ":>>>" + BleController.getInstance().bytesToHexString(bytes));

            BleController.getInstance().writeBuffer(bytes, new OnWriteCallback() {
                @Override
                public void onSuccess() {
                    Toast.makeText(getActivity(), name + "写入成功！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailed(int state) {
                    Toast.makeText(getActivity(), name + "写入失败！", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (ModbusError e) {
            Toast.makeText(getActivity(), name + "写入异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        } catch (NumberFormatException e) {
            Toast.makeText(getActivity(), name + "的值格式不正确", Toast.LENGTH_SHORT).show();
        }
    }

    public void exitFragment() {
        BleController.getInstance().unregistReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY);
    }

    public void enterFragment() {
        BleController.getInstance().unregistReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY);
        
        // 接收数据的监听
        BleController.getInstance().registReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY, new OnReceiverCallback() {
            @Override
            public void onRecive(byte[] value) {
                if (binding == null) {
                    return;
                }

                System.out.println("接收：>>" + BleController.getInstance().bytesToHexString(value));
                
                // 检查响应长度
                if (value.length < 5) {
                    return;
                }

                // 检查是否是读取保持寄存器的响应 (功能码0x03)
                if (value[1] != 0x03) {
                    return;
                }

                // 获取数据长度
                int dataLength = value[2] & 0xFF;
                
                // 如果是批量读取响应
                if (isBatchReading) {
                    // 检查数据长度是否匹配：应该返回 BATCH_READ_REGISTER_COUNT * 2 个字节
                    int expectedDataLength = BATCH_READ_REGISTER_COUNT * 2;
                    if (dataLength != expectedDataLength) {
                        System.out.println("批量读取数据长度不匹配，期望：" + expectedDataLength + "，实际：" + dataLength);
                        isBatchReading = false;
                        return;
                    }
                    
                    // 提取数据部分（跳过设备地址、功能码、字节数，最后2个字节是CRC）
                    byte[] dataBytes = Arrays.copyOfRange(value, 3, 3 + dataLength);
                    
                    // 遍历所有地址，从批量数据中提取对应的值
                    for (java.util.Map.Entry<Integer, EditText> entry : addressToEditTextMap.entrySet()) {
                        int address = entry.getKey();
                        EditText editText = entry.getValue();
                        
                        Float extractedValue = extractFloatValueFromBatchData(dataBytes, address);
                        if (extractedValue != null) {
                            editText.setText(String.valueOf(extractedValue));
                        }
                    }
                    
                    isBatchReading = false;
                    Toast.makeText(getActivity(), "所有值读取完成！", Toast.LENGTH_SHORT).show();
                } else {
                    // 单个读取响应（保留原有逻辑，用于单个写入后的读取确认等）
                    // 检查数据长度：应该返回4个字节（2个寄存器）
                    if (dataLength != 4) {
                        return;
                    }

                    // 解析Float值：跳过前3个字节（设备地址、功能码、字节数），取4个字节的数据
                    byte[] dataBytes = Arrays.copyOfRange(value, 3, 7);
                    float floatValue = ByteUtil.bytesToFloat(dataBytes);

                    // 根据当前读取的地址更新对应的UI
                    EditText editText = addressToEditTextMap.get(currentReadAddress);
                    if (editText != null) {
                        editText.setText(String.valueOf(floatValue));
                    }

                    currentReadAddress = -1;
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        enterFragment();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        exitFragment();
        binding = null;
    }
}

